<template>
  <div class="xunni-scroll">
    <div class="container" @scroll="scrollActive">
      <div class="ul-box" :style="`height:${allHeight}px;`">
        <div
          v-for="item in listArr"
          :key="item.id"
          class="item"
          :style="`transform: translateY(${offsetY}px);`"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      listArr: [],
      allList: [],
      offsetY: 0,
      showNum: 10,
      allHeight: 100,
      itemHeight: 30,
    };
  },
  created() {
    for (let i = 0; i < 10000; i++) {
      this.allList.push({
        id: i + 1,
        name: `小溪流${i + 1}`,
      });
    }
    this.initData();
  },
  methods: {
    initData() {
      this.listArr = this.allList.slice(0, this.showNum);
      this.allHeight = this.allList.length * this.itemHeight;
    },
    scrollActive(e) {
      let scrollTop = e.target.scrollTop;
      this.offsetY = scrollTop - (scrollTop % this.itemHeight);
      this.listArr = this.allList.slice(
        Math.floor(scrollTop / this.itemHeight),
        Math.floor(scrollTop / this.itemHeight) + this.showNum
      );
    },
  },
};
</script>

<style scoped lang="scss">
.xunni-scroll {
  display: flex;
  justify-content: center;
  .container {
    height: 300px;
    width: 150px;
    overflow: auto;
    border: 1px solid red;
  }
}
.ul-box {
  height: 5000px;
  overflow: hidden;
  .item {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    //这个属性也可以优化大量列表的渲染性能
    // content-visibility: auto;
    // contain-intrinsic-size: 300px;
  }
}
</style>
